package day_01.observer_mode;

import java.util.ArrayList;
import java.util.List;

public class WeatherData implements Subject {
    private List<Observer> observers;

    // 温度
    private float temp;
    // 湿度
    private float humidity;
    // 气压
    private float pressure;

    public WeatherData() {
        this.observers = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        int index = observers.indexOf(o);
        if(index >= 0) observers.remove(index);
    }

    @Override
    public void notifyObserver() {
        for(Observer o: observers){
            o.update(temp, humidity, pressure);
        }
    }

    /**
     * 从气象站得到更新的观测值，通知观察者
     */
    public void measurementsChanged(){
        notifyObserver();
    }

    /**
     * 气象站设置新的值
     */
    public void setMeasurements(float temp, float humidity, float pressure){
        this.temp = temp;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }
}
